package com.xuecheng.order.mq;

import com.xuecheng.framework.domain.task.XcTask;
import com.xuecheng.order.config.RabbitMQConfig;
import com.xuecheng.order.service.XcTaskService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * @author ShengJinFeng
 * @version V1.0
 * @ClassName ChooseCourseTask
 * @Description (选课任务类)
 * @date 2020/3/13 19:04
 * @since V1.0
 */
@Component
public class ChooseCourseTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(ChooseCourseTask.class);

    @Autowired
    private XcTaskService xcTaskService;

    /**
     * @Description 每隔1分钟，执行扫描选课任务
     * @author ShengJinFeng
     * @date 2020/3/13
     */
    //@Scheduled(cron = "0 0/1 * * * *")
    @Scheduled(cron = "0/5 * * * * *")
    public void ChooseCourseTask(){
        //获取1分钟之前的时间
        Calendar calendar =new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(GregorianCalendar.MINUTE,-1);
        Date time = calendar.getTime();
        List<XcTask> list = xcTaskService.queryTaskUpdateTimeBefore(time, 100);
        System.out.println(list);
        if (CollectionUtils.isEmpty(list)){
            return;
        }
        list.forEach(xcTask -> {
            //检查任务是否可以执行
            XcTask task = xcTaskService.checkTask(xcTask);
            if (task != null){
                //发送消息
                xcTaskService.sendMsg(task);
                LOGGER.info("send choose course task_id:{}",xcTask.getId());
            }
        });
    }

    /**
     * @Description 监听完成任务消息
     * @author ShengJinFeng
     * @date 2020/3/14
     */
    @RabbitListener(queues = RabbitMQConfig.XC_LEARNING_FINISHADDCHOOSECOURSE)
    public void receiveFinishChoosecourseTask(XcTask xcTask){
        if (xcTask != null || StringUtils.isNotEmpty(xcTask.getId())){
            LOGGER.info("receiveChoosecourseTask...{}",xcTask.getId());
            //删除任务，添加历史任务
            xcTaskService.finishTask(xcTask.getId());
        }
    }
}
